import axios from 'axios'
import { ElMessage } from 'element-plus'
import { getToken, removeToken } from '@/utils/auth'
import router from '@/router'

const service = axios.create({
    baseURL: 'http://192.168.0.13:7000/apis', // 与网关配置对应
})

// 请求拦截器
service.interceptors.request.use(
    config => {
        const token = getToken()
        if (token) {
            config.headers['Authorization'] = 'Bearer ' + token
        }
        return config
    },
    error => {
        return Promise.reject(error)
    }
)

// 响应拦截器
service.interceptors.response.use(
    response => {
        const res = response.data
        // 如果是返回的文件
        if (response.config.responseType === 'blob') {
            return response
        }

        // 正常返回数据
        if (res.code === 200) {
            return res
        }

        if (res.code !== 200) {
            ElMessage.error(res.message || '请求失败')
            if (res.code === 401) {
                removeToken()
                router.push('/login')
            }
            return Promise.reject(new Error(res.message || '请求失败'))
        }
        return res
    },
    error => {
        ElMessage.error(error.message || '请求失败')
        return Promise.reject(error)
    }
)

export default service


